package cn.fresh.xuanyuan.module.system.model.request;

import com.alibaba.fastjson.JSONObject;
import com.douyin.openapi.client.Client;
import com.douyin.openapi.client.models.V2Jscode2sessionRequest;
import com.douyin.openapi.client.models.V2Jscode2sessionResponse;
import com.douyin.openapi.credential.models.Config;
import com.xingyuv.jushauth.cache.AuthStateCache;
import com.xingyuv.jushauth.config.AuthConfig;
import com.xingyuv.jushauth.config.AuthSource;
import com.xingyuv.jushauth.enums.AuthResponseStatus;
import com.xingyuv.jushauth.exception.AuthException;
import com.xingyuv.jushauth.log.Log;
import com.xingyuv.jushauth.model.AuthCallback;
import com.xingyuv.jushauth.model.AuthResponse;
import com.xingyuv.jushauth.model.AuthToken;
import com.xingyuv.jushauth.model.AuthUser;
import com.xingyuv.jushauth.request.AuthDefaultRequest;
import com.xingyuv.jushauth.request.AuthWeChatMiniAppRequest;
import com.xingyuv.jushauth.utils.AuthChecker;
import com.xingyuv.jushauth.utils.HttpUtils;
import com.xingyuv.jushauth.utils.UrlBuilder;

public class AuthDouYinMiniAppRequest extends AuthDefaultRequest {
    public AuthDouYinMiniAppRequest(AuthConfig config, AuthSource source) {
        super(config, source);
    }

    public AuthDouYinMiniAppRequest(AuthConfig config, AuthSource source, AuthStateCache authStateCache) {
        super(config, source, authStateCache);
    }

    @Override
    protected AuthToken getAccessToken(AuthCallback authCallback) {
        try {
            Config config = new Config().setClientKey(this.config.getClientId()).setClientSecret(this.config.getClientSecret());
            Client client = new Client(config);
            V2Jscode2sessionRequest sdkRequest = new V2Jscode2sessionRequest();
//            sdkRequest.setAnonymousCode(authCallback.getCode());
            sdkRequest.setAppid(this.config.getClientId());
            sdkRequest.setCode(authCallback.getCode());
            sdkRequest.setSecret(this.config.getClientSecret());
            V2Jscode2sessionResponse sdkResponse = client.V2Jscode2session(sdkRequest);

            assert sdkResponse != null;
            this.checkResponse(sdkResponse);
            return AuthToken.builder().openId(sdkResponse.getData().getOpenid()).unionId(sdkResponse.getData().getUnionid()).build();
        }
        catch (Exception e) {
            throw new AuthException(e.getMessage());
        }
    }

    public AuthResponse login(AuthCallback authCallback) {
        try {
            this.checkCode(authCallback);
            if (!this.config.isIgnoreCheckState()) {
                AuthChecker.checkState(authCallback.getState(), this.source, this.authStateCache);
            }

            AuthToken authToken = this.getAccessToken(authCallback);
            AuthUser user = this.getUserInfo(authToken);
            return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build();
        } catch (Exception var4) {
            Log.error("Failed to login with oauth authorization.", var4);

        }
        return AuthResponse.builder().code(AuthResponseStatus.FAILURE.getCode()).msg("请求失败").build();
    }

    @Override
    protected String accessTokenUrl(String code) {
        return UrlBuilder.fromBaseUrl(this.source.accessToken()).queryParam("code", code).queryParam("client_id", this.config.getClientId()).queryParam("client_secret", this.config.getClientSecret()).queryParam("grant_type", "authorization_code").queryParam("redirect_uri", this.config.getRedirectUri()).build();
    }

    private void checkResponse(V2Jscode2sessionResponse response) {
        if (response.getErrNo() != 0) {
            throw new AuthException(response.getErrNo().intValue(), response.getErrTips());
        }
    }

    @Override
    protected AuthUser getUserInfo(AuthToken authToken) {
        return AuthUser.builder().username("").nickname("").avatar("").uuid(authToken.getOpenId()).token(authToken).source(this.source.toString()).build();
    }
}
